package cn.exrick.xboot.flow.service.serviceimpl;

import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SecurityUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.flow.entity.FlowTemplateinfo;
import cn.exrick.xboot.flow.service.IFlowTemplateinfoService;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.content.dao.HontDepartmentHeaderDao;
import cn.exrick.xboot.modules.content.dao.mapper.HontUserMapper;
import cn.exrick.xboot.modules.content.entity.HontDepartmentHeader;
import cn.exrick.xboot.modules.content.entity.HontUser;
import cn.exrick.xboot.modules.content.entity.HontVo.HontUserRolelevelQueryVo;
import cn.exrick.xboot.modules.content.entity.HontVo.HontUserRolelevelVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.exrick.xboot.flow.entity.FlowUserinfo;
import cn.exrick.xboot.flow.mapper.FlowUserinfoMapper;
import cn.exrick.xboot.flow.service.IFlowUserinfoService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zy
 * @since 2022-08-31
 */
@Service
@Transactional
public class FlowUserinfoServiceImpl extends ServiceImpl<FlowUserinfoMapper, FlowUserinfo> implements IFlowUserinfoService {


    @Autowired
    private FlowUserinfoMapper flowUserinfoMapper;
    @Autowired
    private IFlowTemplateinfoService ifFlowTemplateinfoService;
    @Autowired
    private SecurityUtil securityUtil;
    @Autowired
    private HontUserMapper hontUserMapper;
    @Autowired
    private HontDepartmentHeaderDao hontDepartmentHeaderDao;


    @Override
    public IPage<FlowUserinfo> selectPage(Page<FlowUserinfo> page, FlowUserinfo flowUserinfo) {
        QueryWrapper<FlowUserinfo> query = Wrappers.query();
        QueryWrapper<FlowUserinfo> entityWrapper = getEntityWrapper(query, flowUserinfo);
        return flowUserinfoMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<FlowUserinfo> selectList(FlowUserinfo flowUserinfo) {
        QueryWrapper<FlowUserinfo> query = Wrappers.query();
        QueryWrapper<FlowUserinfo> entityWrapper = getEntityWrapper(query, flowUserinfo);
        return flowUserinfoMapper.selectList(entityWrapper);
    }

    @Override
    public boolean checkAuth(String templateId,String templateVersion, User u) {
        QueryWrapper<FlowUserinfo> query = Wrappers.query();
        query.lambda().eq(FlowUserinfo::getDataType,FlowUserinfo.DATA_TYPE_ACCESS)
                .eq(FlowUserinfo::getUserRoleId,u.getId())
                 .eq(FlowUserinfo::getTemplateId,templateId)
                .eq(FlowUserinfo::getTemplateVersion,templateVersion);
        int userCount=flowUserinfoMapper.selectCount(query);
        if(userCount>0){
            return true;
        }
        List<String> roles=u.getRoles().stream().map(t->t.getId()).collect(toList());
        QueryWrapper<FlowUserinfo> queryRole = Wrappers.query();
        queryRole.lambda().eq(FlowUserinfo::getDataType,FlowUserinfo.DATA_TYPE_ACCESS)
                .eq(FlowUserinfo::getUserType,FlowUserinfo.USER_TYPE_ROLE)
        .in(FlowUserinfo::getUserRoleId,roles).eq(FlowUserinfo::getTemplateId,templateId)
                .eq(FlowUserinfo::getTemplateVersion,templateVersion);
        List<FlowUserinfo> flowUserinfosRole=flowUserinfoMapper.selectList(queryRole);

        QueryWrapper<FlowUserinfo> queryDepart= Wrappers.query();
        queryDepart.lambda().eq(FlowUserinfo::getDataType,FlowUserinfo.DATA_TYPE_ACCESS)
                .eq(FlowUserinfo::getUserType,FlowUserinfo.USER_TYPE_DEPART)
                .eq(FlowUserinfo::getTemplateId,templateId)
                .eq(FlowUserinfo::getTemplateVersion,templateVersion);
        List<FlowUserinfo> flowUserinfosDeparts=flowUserinfoMapper.selectList(queryDepart);
        List<FlowUserinfo> flowUserinfosDepart=flowUserinfosDeparts.stream().filter(t->u.getDepartmentId().equals(t.getUserRoleId())).collect(toList());
        if(flowUserinfosDeparts.size()>0){
            if(flowUserinfosRole.size()>0&&flowUserinfosDepart.size()>0){
                return true;
            }
        }else {
            if(flowUserinfosRole.size()>0){
                return true;
            }
        }
        return false;
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<FlowUserinfo> getEntityWrapper(QueryWrapper<FlowUserinfo> entityWrapper, FlowUserinfo flowUserinfo) {

        entityWrapper.lambda().eq(StringUtils.isNotBlank(flowUserinfo.getTemplateId()),
                FlowUserinfo::getTemplateId,flowUserinfo.getTemplateId())
                .eq(StringUtils.isNotBlank(flowUserinfo.getTemplateVersion()),FlowUserinfo::getTemplateVersion,flowUserinfo.getTemplateVersion())
                .eq(flowUserinfo.getUserType()!=null,FlowUserinfo::getUserType,
                        flowUserinfo.getUserType())
                .eq(flowUserinfo.getDataType()!=null,FlowUserinfo::getDataType,
                        flowUserinfo.getDataType());
        return entityWrapper;
    }

    @Override
    public void addFlowUserinfos(List<FlowUserinfo> flowUserinfos,String templateId, String templateVersion,Integer userType,Integer dataType) {
        if(flowUserinfos.size()==0){
            return;
        }
        flowUserinfos.forEach(t->
        {
            t.setTemplateId(templateId);
            t.setTemplateVersion(templateVersion);
            t.setUserType(userType);
            t.setDataType(dataType);
        });
        flowUserinfoMapper.insertBatch(flowUserinfos);
    }

    @Override
    public Result<Object> getUserinfoOnHontUser(String templateId) {

        FlowTemplateinfo flowTemplateinfo = ifFlowTemplateinfoService.getById(templateId);
        //查询当前模板下 被考核人数据
        QueryWrapper<FlowUserinfo> query = Wrappers.query();
        query.lambda().eq(FlowUserinfo::getTemplateId,templateId)
                .eq(FlowUserinfo::getTemplateVersion,flowTemplateinfo.getTemplateVersion())
                .eq(FlowUserinfo::getDataType,FlowUserinfo.DATA_TYPE_BEINGACCESS);
        List<FlowUserinfo> flowUserinfos=flowUserinfoMapper.selectList(query);
        //过滤被考核人 被考核角色 被考核部门
        List<String> flowUserinfosUser=flowUserinfos.stream().filter(t->FlowUserinfo.USER_TYPE_USER.equals(t.getDataType())).map(FlowUserinfo::getUserRoleId).collect(toList());

        List<String> flowUserinfosRole=flowUserinfos.stream().filter(t->FlowUserinfo.USER_TYPE_ROLE.equals(t.getDataType())).map(FlowUserinfo::getUserRoleId).collect(toList());

        List<String> flowUserinfosDepart=flowUserinfos.stream().filter(t->FlowUserinfo.USER_TYPE_DEPART.equals(t.getDataType())).map(FlowUserinfo::getUserRoleId).collect(toList());
        //组装查询用户数据
        HontUserRolelevelQueryVo hontUserRolelevelQueryVo=new HontUserRolelevelQueryVo();
        hontUserRolelevelQueryVo.setUserIds(flowUserinfosUser);
        //组装查询部门与角色数据
        HontUserRolelevelQueryVo hontUserRolelevelQueryVo1=new HontUserRolelevelQueryVo();
        hontUserRolelevelQueryVo1.setRoleIds(flowUserinfosRole);
        hontUserRolelevelQueryVo1.setDepartmentIds(flowUserinfosDepart);
        //该流程添加组装架构筛选
        if(flowTemplateinfo.getIsOrganization()==1){
            HontUser u = securityUtil.getCurrUser();
            List<HontDepartmentHeader> byHontUserId = hontDepartmentHeaderDao.findByHontUserId(u.getId());
            List<String> deptIds =byHontUserId.stream().map(t->t.getHontDepartmentId()).collect(toList());
            hontUserRolelevelQueryVo.setDepartmentIds(deptIds);
            //获取当前登录用户与被审核人部门交集
            if(flowUserinfosDepart.size()>0){
                List<String> intersection = flowUserinfosDepart.stream().filter(item -> deptIds.contains(item)).collect(toList());
                hontUserRolelevelQueryVo1.setDepartmentIds(intersection);
            }else {
                hontUserRolelevelQueryVo1.setDepartmentIds(deptIds);

            }
        }
        List<HontUserRolelevelVo> hontUserRolelevelVoList= hontUserMapper.getUserByDepartAndUserId(hontUserRolelevelQueryVo);
        List<HontUserRolelevelVo> hontUserRolelevelVoList1= hontUserMapper.getUserByDepartAndUserId(hontUserRolelevelQueryVo1);
        hontUserRolelevelVoList.addAll(hontUserRolelevelVoList1);
        List<HontUserRolelevelVo> data=hontUserRolelevelVoList.stream().distinct().collect(toList());

        return ResultUtil.data(data);
    }
}
